package com.cy.dda.comm.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Map;

/**
 * @description: spring el 工具
 * @author: Ocean
 * @create: 2018-08-02 19:23
 **/
@Slf4j
public class SpringELUtils {

    private static final ExpressionParser parser = new SpelExpressionParser();
    private static final ParserContext parserContext = new TemplateParserContext("{", "}");

    public static <T> T getValue(String expression, Map<String, Object> params, Class<T> valueType) {
        StandardEvaluationContext context = new StandardEvaluationContext();
        params.forEach((k, v) -> {
            context.setVariable(k, v);
        });

        Expression exp = parser.parseExpression(expression, parserContext);
        return (T) exp.getValue(context);
    }

    public static String getValue(String expression, Map<String, Object> params) {
        return getValue(expression, params, String.class);
    }

    public static String getValue(String expression, Object object) {
        Map<String, Object> params = JsonObjectMapper.read(object, Map.class);
        return getValue(expression, params, String.class);
    }

}
